/*
 * Copyright 2016 Wealth Inc. All rights reserved.
 */
 package com.wealth.bank.service.impl;

import iaas.enums.StatusEnum;
import iaas.persistence.DynamicSpecifications;
import iaas.persistence.SearchFilter;
import iaas.persistence.SearchFilter.Operator;
import iaas.repository.BaseRepository;
import iaas.service.impl.BaseServiceImpl;
import iaas.utils.Reflections;
import iaas.web.JqGridRequest;

import java.util.Collection;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import com.wealth.bank.entity.Picked;
import com.wealth.bank.repository.PickedDao;
import com.wealth.bank.service.IPickedService;

/**
 * @author chan
 * @version 1.0
 * @since 1.0
 */
 
@Component
public class PickedServiceImpl extends BaseServiceImpl<Picked> implements IPickedService{

	@Autowired
	private PickedDao pickedDao;
	@Autowired
	private BaseRepository<Picked,Long> baseRepository;
	
	@Override
	public Page<Picked> getPicked(Long corpid, JqGridRequest request,
			Class<Picked> clz) throws Exception {
		//创建分页请求.
				int pageNumber = request.getPage();
				int pageSize = request.getRows();
				String sortType = StringUtils.isEmpty(request.getSidx())?"id":request.getSidx();
				String sortDirection = StringUtils.isEmpty(request.getSord())?"desc":request.getSord();
				Direction direction = sortDirection.equals("desc")?Direction.DESC:Direction.ASC;
				Sort sort = new Sort(direction, sortType);
				PageRequest pageRequest = new PageRequest(pageNumber - 1, pageSize, sort);

				//创建动态查询条件组合.
				Collection<SearchFilter> filters = SearchFilter.parse(request);
				//过滤:企业
				if(Reflections.existsField("corp", clz)){
					if(corpid!=1L){
						filters.add(new SearchFilter("corp.id", Operator.EQ, corpid));
					}
				}
				//过滤:状态
				if(Reflections.existsField("status", clz)){
					filters.add(new SearchFilter("status", Operator.NE, StatusEnum.DELETE.getValue()));
				}
				Specification<Picked> spec = DynamicSpecifications.bySearchFilter(filters, clz);
				return baseRepository.findAll(spec, pageRequest);
	}

	
	@Override
	public List<Picked> findByStatusAndDistrictId(Integer status,
			Long districtId) {
		
		return pickedDao.findByStatusAndDistrictId(status, districtId);
	}
	
}
